﻿using System.Linq;
using System.Threading.Tasks;
using Furion.Authorization;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Admin.Core;

namespace Admin.Web.Core.Handlers
{
    /// <summary>
    /// 授权检查
    /// </summary>
    public class JwtHandler : AppAuthorizeHandler
    {
        public override async Task<bool> PipelineAsync(AuthorizationHandlerContext context, DefaultHttpContext httpContext)
        {
            return await CheckAuthorzieAsync(httpContext);
        }

        /// <summary>
        /// 检查权限
        /// </summary>
        /// <param name="httpContext"></param>
        /// <returns></returns>
        private static async Task<bool> CheckAuthorzieAsync(DefaultHttpContext httpContext)
        {
            // 获取权限特性
            var securityDefineAttribute = httpContext.GetMetadata<SecurityDefineAttribute>();
            if (securityDefineAttribute == null) return true;

            // 解析服务
            var opeManager = httpContext.RequestServices.GetService<IOperator>();
            var securities = await opeManager.GetSecuritiesAsync(opeManager.UserId);

            // 检查授权
            return securities.Select(s => s.Perms).Contains(securityDefineAttribute.ResourceId);
        }
    }
}